package com.kawaiim.zhj;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Bundle;
import android.os.PowerManager;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TableRow;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;

import java.util.Random;


import com.kawaiim.zhj.GameProcess.GameProcess;
import com.kawaiim.zhj.GameProcess.GameProcessEnum;
import com.kawaiim.zhj.Operator.LordGameMode;
import com.kawaiim.zhj.GameAnimation.DeckOperator;
import com.kawaiim.zhj.GameAnimation.PokeOperator;
import com.kawaiim.zhj.GameAnimation.CardAnimator;
import com.kawaiim.zhj.Operator.PeopleOperator;
import com.kawaiim.zhj.Sound.GameEffectPlay;
import com.kawaiim.zhj.entity.Player;
import com.kawaiim.zhj.utilities.Constants;
import com.kawaiim.zhj.utilities.DensityUtil;
import com.kawaiim.zhj.utilities.HomeWatcher;
import com.kawaiim.zhj.utilities.RandomName;

public class LandlordActivity extends AppCompatActivity {


    public PeopleOperator peopleOperator;   //业务类，对四人队列进行操作
    public Player  players[] = new Player[Constants.PLAYERS_SIZE];        //四个人的队列
    public int redThree;        //谁先出牌
    public TextView lbl_bottomscore;//积分

    public int[] integration = new int[1];     //当前局数的积分，Integer不能传引用
    public Random ran;     //随机函数

    public CardView[] poke = new CardView[Constants.MAX_CARD_NUM];       //52张卡
    public TextView[] temptPoke = new TextView[Constants.MAX_CARD_NUM];       //52张卡（保存位置）

    public  static TextView[] mes = new TextView[4];          //四个人的信息
    public TextView[] four_action_pic = new TextView[4];     //显示图片（1分、不叫）
    public TextView breakrule;     //规则不符合
    public TextView cannotOutHint;     //不能出牌
    public CardView start_button;  //开始按钮
    public CardView [] outCardThreebtn = new CardView[3];     //出牌,不出,提示
    public TextView [] twoFunbtn = new TextView[2];     //2个功能按钮图标
    public TextView[][] end_panel_score = new TextView[4][]; //结束计分按钮
    private TextView end_panel_close; //结束的积分榜的差
    private LinearLayout end_panel_table; //结束的积分榜上的表格
    public CardView end_score_panel; //结束的积分榜上的表格
    public TableRow [] end_panel_row = new TableRow[4]; //结束的积分榜上的表格的对应行

    public Boolean isHosting;     //是否处于托管状态
    public Boolean isSoundEffectOpen = true; //是否可以播放音效

    public GameEffectPlay soundEffect;  //音效播放
    public RelativeLayout landlord_layout; //landlord相对布局
    public Display d;  //保存当前系统的长宽px
    public Resources resources;  //获取当前系统的资源
    public int card_interval;  //card_interval的px版
    public int card_small_interval;  //CARD_SMALL_INTERVAL的px版
    public TextView[] peoplesImage = new TextView[4];//创建四人头像

    public PokeOperator pokeOperator;//设置卡牌图片
    public DeckOperator deckOperator;//对卡牌的操作类
    public GameProcess process; //游戏的流程
    private HomeWatcher mHomeWatcher;   //监听home键
    private PowerManager pm;
    private  PowerManager.WakeLock wl;
    //endregion

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_landlord);

        //隐藏状态栏和虚拟按键
        hideActionBar();
        soundEffect = new GameEffectPlay(getApplicationContext());
        //getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        initGameLandLord();  //初始化界面各控件，各变量，各信息
    }

    //隐藏状态栏和虚拟按键
    private void hideActionBar() {
        //隐藏顶部的标题栏
        this.getSupportActionBar().hide();
        //隐藏虚拟按键
        View decorView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
        decorView.setSystemUiVisibility(uiOptions);
    }
    //初始化界面各控件，各变量，各信息
    private void initGameLandLord() {
        //初始化对应各控件
        initFindWidget();

        //刚进入游戏后初始化所有变量
        initVariable();
        InitalPoke(); //初始化52张牌的标签
        inithomeWatcher();      //初始化home键的监听事件，按下后声音关闭
        //初始化刚进入游戏的显示状态
        initViewDisplay();
        //对玩家信息的初始化
        process.startGameProcess.initGame();

        //设置长按将牌放下的监听事件
        landlord_layout.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                //只有在发完牌阶段且在结束游戏阶段之前
                if (process.step.compareTo(GameProcessEnum.DEAL_CARD_PROCESS) > 0
                        && process.step.compareTo(GameProcessEnum.End_GAME_PROCESS) < 0) {
                    //长按将牌放下
                    putDownPoke();
                }
                return true;
            }
        });

    }



    //初始化，find对应各控件
    private void initFindWidget() {
        //初始化landlord相对布局
        landlord_layout = (RelativeLayout) findViewById(R.id.landlord);
        //初始化四人的名字
        mes[0] = (TextView) findViewById(R.id.down_mes);
        mes[1] = (TextView) findViewById(R.id.right_mes);
        mes[2] = (TextView) findViewById(R.id.up_mes);
        mes[3] = (TextView) findViewById(R.id.left_mes);
        //初始化四人的显示信息
        four_action_pic[0] = (TextView) findViewById(R.id.down_score);
        four_action_pic[1] = (TextView) findViewById(R.id.right_score);
        four_action_pic[2] = (TextView) findViewById(R.id.up_score);
        four_action_pic[3] = (TextView) findViewById(R.id.left_score);
        //初始化不能出，出错信息
        breakrule = (TextView) findViewById(R.id.breakrule);
        cannotOutHint = (TextView) findViewById(R.id.cannotout);
        //初始化出牌三按钮
        outCardThreebtn[0] = (CardView) findViewById(R.id.outcard);
        outCardThreebtn[1] = (CardView) findViewById(R.id.refuse);
        outCardThreebtn[2] = (CardView) findViewById(R.id.hint);
        //初始化四个人的图片
        peoplesImage[0] = (TextView)findViewById(R.id.down_people);
        peoplesImage[1] = (TextView)findViewById(R.id.right_people);
        peoplesImage[2] = (TextView)findViewById(R.id.up_people);
        peoplesImage[3] = (TextView)findViewById(R.id.left_people);
        //初始化开始按钮
        start_button = (CardView) findViewById(R.id.start);
        //初始化四个功能按钮和明牌的图标
        twoFunbtn[0] = (TextView) findViewById(R.id.robot);
        twoFunbtn[1] = (TextView) findViewById(R.id.soundeffect);
        //初始化总积分
        lbl_bottomscore = (TextView) findViewById(R.id.bottom);
        //初始化各按钮的触摸变透明的监听事件
        TouchListener touchListener = new TouchListener();
        start_button.setOnTouchListener(touchListener);
        for (int i = 0; i < 4; i++) {

            if (i < 3) {
                outCardThreebtn[i].setOnTouchListener(touchListener);
            }
            if(i < 2 ) {
                twoFunbtn[i].setOnTouchListener(touchListener);
            }
            peoplesImage[i].setOnTouchListener(touchListener);
            mes[i].setOnTouchListener(touchListener);
        }

        start_button.setBackground(getDrawable(R.mipmap.start_button));
        outCardThreebtn[0].setBackground(getDrawable(R.mipmap.outcard_button));
        outCardThreebtn[1].setBackground(getDrawable(R.mipmap.refuse));
        outCardThreebtn[2].setBackground(getDrawable(R.mipmap.hint_button));
    }

    //刚进入游戏后初始化所有变量
    private void initVariable() {
        //初始化随机种子
        ran = new Random();

        //初始化环境资源
        resources = getApplicationContext().getResources();
        //获取当前系统
        WindowManager wm = (WindowManager)getSystemService(WINDOW_SERVICE);
        //初始化当前手机的长宽比
        d = wm.getDefaultDisplay();
        //初始化px版的card_interval
        card_interval = DensityUtil.dip2px(getApplicationContext(), Constants.CARD_INTERVAL);
        card_small_interval = DensityUtil.dip2px(getApplicationContext(), Constants.CARD_SMALL_INTERVAL);

        //初始化卡牌效果类
        pokeOperator = new PokeOperator(this);
        deckOperator = new DeckOperator(this);
        //初始化游戏的流程
        process = new GameProcess(this);

        //初始化四人、牌堆、出牌的队列
        peopleOperator = new PeopleOperator(new LordGameMode());
        //对玩家信息进行初始化
        for (int i = 0; i < 4; i++) {
            players[i]=new Player(this);
        }

        //游戏重新开始时初始化所有的变量
        refreshAllVariable();
    }
    //游戏重新开始时初始化所有的变量
    private void refreshAllVariable() {
        isHosting = false;    //机器人托管初始化
        redThree = -1;       //初始化没有红三
        integration[0] = 1;     //初始化当前局数的积分
        //初始化每个人的信息
        for (int i = 0; i < Constants.PLAYERS_SIZE; i++) {
            mes[i].setText(RandomName.getRandomName());
            mes[i].setTextColor(Color.WHITE);
            //players[i].setName(RandomName.getRandomName(),Color.WHITE);
            players[i].Init_AfterTurn();//对4个队列进行初始化操作


        }
    }
    //初始化刚进入游戏的显示状态
    private void initViewDisplay() {

        breakrule.setVisibility(View.INVISIBLE);//提示有问题隐藏
        cannotOutHint.setVisibility(View.INVISIBLE);//提示不能出隐藏
        for (int i = 0; i < Constants.PLAYERS_SIZE; i++) {
            if (i < 3) {
                outCardThreebtn[i].setVisibility(View.GONE);//出牌三按钮已经隐藏
            }

        }

    }

    //按钮触摸监听
    // 实现点击后半透明，手指移开后恢复
    // 判断手指移开后，是否停留在原按钮上，没有停留则不相当于按
    class TouchListener implements View.OnTouchListener {

        @SuppressLint({"NonConstantResourceId", "ClickableViewAccessibility"})
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:   //手指第一次触摸到屏幕
                    //第一次触碰透明度减半
                    soundEffect.pressButton();
                    v.setAlpha(0.5f);
                    break;
                case MotionEvent.ACTION_UP:     //放开后透明度还原，同时触发点击事件
                    v.setAlpha(1.0f);
                    Point mouseOff2 = new Point((int)event.getRawX(), (int)event.getRawY());
                    int []location = new int[2];
                    v.getLocationInWindow(location);
                    if (location[0] <= mouseOff2.x
                            && location[1] <= mouseOff2.y
                            && location[0] + v.getWidth() >= mouseOff2.x
                            && location[1] + v.getHeight() >= mouseOff2.y) {
                        int id = v.getId();
                        if (id == R.id.robot) {
                            robot_Click();
                        } else if (id == R.id.soundeffect) {
                            sound_effect_btn_Click();
                        } else if (id == R.id.start) {
                            start_button_Click();
                        } else if (id == R.id.outcard) {
                            outcard_Click();
                        } else if (id == R.id.refuse) {
                            refuse_button_Click();
                        } else if (id == R.id.hint) {
                            hint_button_Click();
                        } else {
                            throw new IllegalStateException("Unexpected value: " + v.getId());
                        }
                    }
                    break;
            }
            return true;
        }
    }

    //右上角积分按钮缩放的点击事件
    //初始化52张牌，和33张用来保存扑克位置信息的无图扑克
    @SuppressLint("ClickableViewAccessibility")
    private void InitalPoke() {
        //初始化52个标签
        pokeClickListener listener = new pokeClickListener();
        for (int i = 0; i < Constants.MAX_CARD_NUM; i++) {
            poke[i] = new CardView(getApplicationContext());
            poke[i].setOnClickListener(listener);
            //设置最小长宽
            poke[i].setMinimumWidth(DensityUtil.dip2px(getApplicationContext(), Constants.CARD_SMALL_WIDTH));
            poke[i].setMinimumHeight(DensityUtil.dip2px(getApplicationContext(), Constants.CARD_SMALL_HEIGHT));
            poke[i].setCardElevation(DensityUtil.dip2px(getApplication(), Constants.ElEVATION_DP));

            //设置通过滑动来选择牌的效果（变为阴影，上移）
            poke[i].setOnTouchListener(pokeOperator);
        }
        for (int i = 0; i < Constants.MAX_CARD_NUM; i++) {
            temptPoke[i] = new TextView(getApplicationContext());
            temptPoke[i].setWidth(DensityUtil.dip2px(this, Constants.CARD_WIDTH));
            temptPoke[i].setHeight(DensityUtil.dip2px(this, Constants.CARD_HEIGHT));
        }

    }
    //为牌设置监听事件
    private class pokeClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            //将扑克牌放下或上提
            pokeOperator.pokeClick(v);
        }
    }
    //endregion

    //region 玩家出牌和电脑出牌、玩家按钮事件实现处
    //开始按钮的事件
    public void start_button_Click()  {
        process.startGameProcess.startPrepareGame();
    }


    //down玩家出牌
    private void outcard_Click() {
        process.outCardProcess.playerOutCard();
    }
    //将下家在上面的牌放下来
    private void putDownPoke() {
        process.outCardProcess.putDownPoke();
    }
    //提示出牌按钮
    private void hint_button_Click() {
        process.outCardProcess.playerHint();
    }
    //不出的按钮
    private void refuse_button_Click() {
        process.outCardProcess.playerRefuse();
    }

    //region 六个功能按钮和聊天显示处
    //托管的点击事件
    public void robot_Click() {
        process.outCardProcess.playerRobot();
    }

    //音效播放的点击事件
    @SuppressLint("UseCompatLoadingForDrawables")
    private void sound_effect_btn_Click() {
        if (Constants.soundEffectMusicFlag) {
            isSoundEffectOpen = false;
            Constants.soundEffectMusicFlag = false;
            twoFunbtn[1].setBackground(resources.getDrawable(
                    R.mipmap.sound_effect_not_btn, getTheme()));
        } else {
            isSoundEffectOpen = true;
            Constants.soundEffectMusicFlag = true;
            twoFunbtn[1].setBackground(resources.getDrawable(
                    R.mipmap.sound_effect_btn, getTheme()));
        }
    }



    //region 斗地主功能函数实现处
    //更新人的卡组信息
    @SuppressLint("SetTextI18n")
    public void update_mes_cardnum(int who) {
        //更新电脑卡组的数量
        mes[who].setText(mes[who].getText().toString().substring(0,3) + "\n剩余牌：" + Integer.toString(players[who].cards.size()));
    }
    //清空所有变量和扑克牌和底牌，并进行初始化
    public void clearAll() {
        refreshAllVariable();
        removeAllPoke();
    }
    public void removeAllPoke() {
        //移除52张poke牌
        for (int i = 0; i < Constants.MAX_CARD_NUM; i++) {
            if (poke[i] != null) {
                poke[i].setRotationY(0.0f);     //初始化有可能的翻转
                poke[i].setTranslationX(0.0f);
                poke[i].setTranslationY(0.0f);
                poke[i].setScaleX(1.0f);
                poke[i].setScaleY(1.0f);
                landlord_layout.removeView(poke[i]);
            }
        }

    }

    //对出牌三按钮进行隐藏或者显示（true为显示，false为隐藏）
    public void outCardThreebtnVisibility(boolean b) {
        if (b) {
            for (int i = 0; i < 3; i++) {
                outCardThreebtn[i].setVisibility(View.VISIBLE);
                CardAnimator.alphaRun(outCardThreebtn[i], Constants.LIGHT_DURATION_TIME);
            }
        } else {
            for (int i = 0; i < 3; i++) {
                CardAnimator.alphaGoneRun(outCardThreebtn[i], Constants.LIGHT_DURATION_TIME);
            }
        }
    }

    //监听home键，后台时关闭音乐和音效
    private void inithomeWatcher() {
        //监听home键，
        mHomeWatcher = new HomeWatcher(this);
        mHomeWatcher.setOnHomePressedListener(new HomeWatcher.OnHomePressedListener() {
            @Override
            public void onHomePressed() {
                Constants.soundEffectMusicFlag = false;
            }

            @Override
            public void onHomeLongPressed() {
            }
        });
        mHomeWatcher.startWatch();
    }

    //关闭窗体事件，将背景音乐和音效播放关闭
    @Override
    protected void onDestroy() {
        soundEffect.releaseSoundPool();//销毁音效
        super.onDestroy();
    }


    //窗体回归事件，将背景音乐和音效播放恢复
    @Override
    protected void onResume() {

        if (isSoundEffectOpen) {
            Constants.soundEffectMusicFlag = true;
        }
        hideActionBar();
        super.onResume();
    }

    //监听返回按键
    @Override
    public void onBackPressed() {

        //取消监听home键
            mHomeWatcher.stopWatch();
            super.onBackPressed();
    }



}
